package com.pisces.tool.util;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.JsonKit;
import com.pisces.core.BizException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class Util {

	private static Logger logger = LoggerFactory.getLogger(Util.class);

	/**
	 * 获取应用基址
	 * 
	 * @param request
	 * @return
	 */
	public static String getBaseUrl(HttpServletRequest request) {
		String servletPath = request.getServletPath();

		String baseUrl = request.getRequestURL().toString();

		if (!servletPath.equals("/")) {
			baseUrl = baseUrl.replaceAll(servletPath, "");
		}

		if (baseUrl.endsWith("/")) {
			baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
		}

		return baseUrl;
	}

	/**
	 * 获取客户端真实IP
	 * 
	 * @param request
	 * @return
	 */
	public static String getRealIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Real-IP"); // Nginx 传过来的ip
		}

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}

		return ip;
	}

	/**
	 * 尝试通过get调用接口
	 * 
	 * @param apiUrl
	 * @param paramMap
	 * @param totalRetryCount
	 *            重试次数
	 * @return
	 */
	public static JSONObject tryGetJson(String apiUrl, Map<String, Object> paramMap, int totalRetryCount) {
		int retriedCount = 1;
		Map<String, String> params = new HashMap<String, String>();
		if (paramMap != null) {
			Set<String> keySet = paramMap.keySet();
			for (String key : keySet) {
				params.put(key, paramMap.get(key) + "");
			}
		}
		while (true) {
			try {
				logger.info("正在进行第[" + retriedCount + "]次调用[" + apiUrl + "], 参数：" + JsonKit.toJson(paramMap));
				String response = HttpKit.get(apiUrl, params);
				logger.info(response);
				return JSONObject.parseObject(response);

			} catch (Exception e) {
				e.printStackTrace();
				retriedCount++;

				if (retriedCount > totalRetryCount) {
                    logger.error("调用业务系统接口 " + retriedCount + " 次，没有得到正确的返回值");
					throw new BizException("系统繁忙，请稍后再试");
				}
			}
		}
	}
	
	/**
	 * 尝试通过get调用接口
	 * 
	 * @param apiUrl
	 * @param paramMap
	 * @param data
	 * @param totalRetryCount
	 * @return
	 */
	public static JSONObject tryPostJson(String apiUrl, Map<String, Object> paramMap, String data, int totalRetryCount) {
		int retriedCount = 1;
		Map<String, String> params = new HashMap<String, String>();
		if (paramMap != null) {
			Set<String> keySet = paramMap.keySet();
			for (String key : keySet) {
				params.put(key, paramMap.get(key) + "");
			}
		}
		while (true) {
			try {
				logger.info("正在进行第[" + retriedCount + "]次调用[" + apiUrl + "], 参数：" + JsonKit.toJson(paramMap));
				String response = HttpKit.post(apiUrl, params, data);
				logger.info(response);
				return JSONObject.parseObject(response);

			} catch (Exception e) {
				e.printStackTrace();
				retriedCount++;

				if (retriedCount > totalRetryCount) {
					throw new BizException("系统繁忙，请稍后再试");
				}
			}
		}
	}

}
